package com.usian.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usian.constants.user.UserConstants.AdminConstans;
import com.usian.feign.ArticleFeign;
import com.usian.feign.WmUserFeign;
import com.usian.mapper.ApUserMapper;
import com.usian.mapper.ApUserRealnameMapper;
import com.usian.model.article.pojos.ApAuthor;
import com.usian.model.base.BaseServiceImpl;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.media.pojos.WmUser;
import com.usian.model.user.dtos.AuthDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.model.user.pojos.ApUserRealname;
import com.usian.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class ApUserRealnameServiceImpl extends BaseServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    @Autowired
    private ArticleFeign articleFeign;
    @Autowired
    private WmUserFeign wmUserFeign;
    @Autowired
    private ApUserMapper apUserMapper;
    @Override
    public PageResponseResult loadListByStatus(AuthDto dto) {
        //参数为空
        if (dto==null){
            return (PageResponseResult) paramInvalid;
        }
        //检查参数
        dto.checkParam();
        QueryWrapper<ApUserRealname> wrapper = new QueryWrapper<>();
        if (dto.getStatus()!=null){
            wrapper.lambda().eq(ApUserRealname::getStatus,dto.getStatus());
        }
        Page pageParam = new Page(dto.getPage(), dto.getSize());
        IPage page=page(pageParam,wrapper);
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),(int)page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }

    @Override
    @Transactional
    @GlobalTransactional
    public ResponseResult updateStatusById(AuthDto dto, Short status) {
        //1.检查参数
        if (dto==null||dto.getId()==null){
           return paramInvalid;
        }
        if(statusCheck(status)){
            return paramInvalid;
        }
        //2.修改状态
        ApUserRealname apUserRealname = new ApUserRealname();
        apUserRealname.setId(dto.getId());
        apUserRealname.setStatus(status);
        if (dto.getMsg()!=null){
            apUserRealname.setReason(dto.getMsg());
        }
        updateById(apUserRealname);

        //3.认证通过添加自媒体账号和作者账号
        if (status.equals(AdminConstans.PASS_AUTH)){
            ResponseResult createResult = createWmUserAndAuthor(dto);
            if (createResult!=null){
                return createResult;
            }
            //TODO发送通知消息
        }
        return success;
    }


    private ResponseResult createWmUserAndAuthor(AuthDto dto){
        //添加自媒体账号，查询ap_user信息封装到wmuser中
        ApUserRealname aur = getById(dto.getId());
        ApUser apUser = apUserMapper.selectById(aur.getUserId());
        if (apUser==null){
            return paramInvalid;
        }
        //检测自媒体用户是否存在
        WmUser wmUser = wmUserFeign.findByName(apUser.getName());
        if (wmUser==null||wmUser.getId()==null){
            wmUser = new WmUser();
            //设置ApUserId
            wmUser.setApUserId(apUser.getId());
            wmUser.setCreatedTime(new Date());
            wmUser.setSalt(apUser.getSalt());
            wmUser.setName(apUser.getName());
            wmUser.setPassword(apUser.getPassword());
            wmUser.setStatus(9);
            wmUser.setPhone(apUser.getPhone());
            wmUserFeign.save(wmUser);
        }
        //创建作者账号
       createAuthor(wmUser);
        //修改ap_user标记
        Short s=1;
        apUser.setFlag(s);
        apUserMapper.updateById(apUser);
        return null;
    }
    /**
     * 创建自媒体账号
     * @param wmUser
     * @return
     */
    private void createAuthor(WmUser wmUser) {
        Integer apUserId = wmUser.getApUserId();
        ApAuthor apAuthor = articleFeign.findByUserId(apUserId);
        if (apAuthor == null) {
            apAuthor = new ApAuthor();
            apAuthor.setName(wmUser.getName());
            apAuthor.setType(AdminConstans.AUTHOR_TYPE);
            apAuthor.setCreatedTime(new Date());
            apAuthor.setUserId(apUserId);
            articleFeign.save(apAuthor);
        }
    }

    /**
     * 状态监测
     * @param status
     * @return
     */
    private boolean statusCheck(Short status) {
        if (status == null
                || ( !status.equals(AdminConstans.FAIL_AUTH)
                && !status.equals(AdminConstans.PASS_AUTH))) {
            return true;
        }
        return false;
    }
}
